package com.atguigu.gmall.user.service.impl;
import com.atguigu.gmall.common.constans.RedisConstant;
import com.atguigu.gmall.common.util.JsonUtil;
import com.atguigu.gmall.common.util.MD5;
import com.atguigu.gmall.model.vo.user.LoginUserResponseVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.gmall.model.user.UserInfo;
import com.atguigu.gmall.user.service.UserInfoService;
import com.atguigu.gmall.user.mapper.UserInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 *
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo>
    implements UserInfoService{
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Override
    public LoginUserResponseVo login(UserInfo userInfo) {
        LoginUserResponseVo responseVo = new LoginUserResponseVo();
        QueryWrapper<UserInfo> infoQueryWrapper = new QueryWrapper<>();
        infoQueryWrapper.eq("login_name", userInfo.getLoginName());
        infoQueryWrapper.eq("passwd", MD5.encrypt(userInfo.getPasswd()));
        UserInfo oneFromDb = userInfoMapper.selectOne(infoQueryWrapper);
        if (oneFromDb == null){
            return null;
        }
        //用户信息不为空，登录成功
        oneFromDb.setIpAddress(userInfo.getIpAddress());
        String token = generateToken(oneFromDb);
        responseVo.setToken(token);
        responseVo.setNickName(oneFromDb.getNickName());

        return responseVo;
    }
    //生成token
    @Override
    public String generateToken(UserInfo userInfo) {
        //生成token
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        //给redis中间件存入token
        redisTemplate.opsForValue().set(RedisConstant.USER_TOKEN_PREFIX + token, Objects.requireNonNull(JsonUtil.toStr(userInfo)),7, TimeUnit.DAYS);
        return token;
    }

    @Override
    public void logout(String token) {
        //在redis中删除token
        redisTemplate.delete(RedisConstant.USER_TOKEN_PREFIX + token);
    }

    @Override
    public LoginUserResponseVo register(UserInfo userInfo) {
        userInfo.setPasswd(MD5.encrypt(userInfo.getPasswd()));

        userInfoMapper.insert(userInfo);
        //数据库中插入用户信息后自动生成id,userInfo属性有id
        String token = generateToken(userInfo);
        LoginUserResponseVo responseVo = new LoginUserResponseVo();
        responseVo.setToken(token);
        responseVo.setNickName(userInfo.getNickName());
        return responseVo;
    }
}




